'''
Author: SlytherinGe
LastEditTime: 2021-07-04 22:07:38
'''
_base_ = '../../_base_/schedules/schedule_1x.py'
model = dict(
    type='FocusFCOS',
    pretrained='open-mmlab://msra/hrnetv2_w32',
    backbone=dict(
        type='HRNet',
        extra=dict(
            stage1=dict(
                num_modules=1,
                num_branches=1,
                block='BOTTLENECK',
                num_blocks=(4, ),
                num_channels=(64, )),
            stage2=dict(
                num_modules=1,
                num_branches=2,
                block='BASIC',
                num_blocks=(4, 4),
                num_channels=(32, 64)),
            stage3=dict(
                num_modules=4,
                num_branches=3,
                block='BASIC',
                num_blocks=(4, 4, 4),
                num_channels=(32, 64, 128)),
            stage4=dict(
                num_modules=3,
                num_branches=4,
                block='BASIC',
                num_blocks=(4, 4, 4, 4),
                num_channels=(32, 64, 128, 256)))),
    neck=dict(
        type='HRFPN',
        in_channels=[32, 64, 128, 256],
        out_channels=256,
        stride=2,
        num_outs=5),
    # paoi_head=None,
    paoi_head=dict(
        type='PAOIHead',
        in_channels=256,
        strides=(8, 16, 32, 64, 128),
        sigma=30,
        pos_thr = 0.8,
        neg_thr = 1e-15,
        target_ratio = 0.05,
        attention_stages=5,
        dcn_on_last_conv=False,
        _detach=True,
        _USE_MASK=True,
        _paoi_sampler='max',
        loss_attention=dict(
            type='GaussianFocalLoss',
            loss_weight=0.5)),
    # bbox_head=None,
    bbox_head=dict(
        type='FocusHead',
        num_classes=1,
        in_channels=256,
        stacked_convs=4,
        feat_channels=256,
        strides=[8, 16, 32, 64, 128],
        regress_ranges=((-1, 64), (64, 128), (128, 256), (256, 512),
                (512, 1e9)),
        loss_cls=dict(
            type='FocalLoss',
            use_sigmoid=True,
            gamma=2.0,
            alpha=0.25,
            loss_weight=1.0),
        loss_bbox=dict(type='IoULoss', loss_weight=1.0),
        loss_centerness=dict(
            type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)),
    # training and testing settings
    train_cfg=dict(
        assigner=dict(
            type='MaxIoUAssigner',
            pos_iou_thr=0.5,
            neg_iou_thr=0.4,
            min_pos_iou=0,
            ignore_iof_thr=-1),
        allowed_border=-1,
        pos_weight=-1,
        debug=False),
    test_cfg=dict(
        nms_pre=1000,
        min_bbox_size=0,
        score_thr=0.05,
        nms=dict(type='nms', iou_threshold=0.5),
        max_per_img=100))

# # dataset settings
dataset_type = 'MyVOCDataset'
data_root = '/media/gejunyao/Disk1/Datasets/SSDD/'
img_norm_cfg = dict(
    mean=[39.7517759, 39.7517759, 39.7517759], std=[ 27.71722963, 27.71722963, 27.71722963], to_rgb=True)
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True),
    dict(type='Resize', img_scale=(640, 640), keep_ratio=False),
    dict(type='EqualizeTransform'),
    dict(type='Rotate', level=5, prob=0.3),
    dict(type='Pad',size_divisor=32),
    dict(type='BrightnessTransform', level=5, prob=0.3),
    dict(type='ContrastTransform', level=5, prob=0.3),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='PAOIGenerate', sigma=None, pos_thr=0.9, sigma_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']),
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(640, 640),
        flip=False,
        transforms=[
            dict(type='Resize', keep_ratio=False),
            dict(type='Pad',size_divisor=32),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='ImageToTensor', keys=['img']),
            dict(type='Collect', keys=['img']),
        ])
]
data = dict(
    samples_per_gpu=12,
    workers_per_gpu=16,
    train=dict(
        type='RepeatDataset',
        times=1,
        dataset=dict(
            type=dataset_type,
            ann_file=[
                data_root + 'VOC2012/ImageSets/Main/trainval.txt'
            ],
            img_prefix=[data_root + 'VOC2012/'],
            pipeline=train_pipeline),
        pipeline=train_pipeline),
    val=dict(
        type=dataset_type,
        ann_file=data_root + 'VOC2012/ImageSets/Main/test.txt',
        img_prefix=data_root + 'VOC2012/',
        pipeline=test_pipeline),
    test=dict(
        type=dataset_type,
        ann_file=data_root + 'VOC2012/ImageSets/Main/test.txt',
        img_prefix=data_root + 'VOC2012/',
        pipeline=test_pipeline))
# evaluation = dict(interval=50, metric='mAP', save_best='mAP')
evaluation = dict(interval=1, metric='mAP', save_best='mAP')
# optimizer
optimizer = dict(
    lr=0.004, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.))
optimizer_config = dict(
    _delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
    policy='step',
    warmup='constant',
    warmup_iters=50,
    warmup_ratio=1.0 / 3,
    # step=[6, 12, 20])
    # step=[16, 20, 23])
    step=[16, 32, 40])
runner = dict(type='EpochBasedRunner', max_epochs=42)
'''
run time
'''
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(
    interval=5,
    hooks=[
        dict(type='TextLoggerHook'),
        dict(type='TensorboardLoggerHook')
    ])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
# load_from = '/media/gejunyao/Disk/Gejunyao/exp_results/mmdetection_files/SSDD/focus/functional_test13/best_mAP.pth'
load_from = None
resume_from = None
workflow = [('train', 1)]
custom_hooks=[dict(type='UpdataTrainingEpochHook')]

if __name__ == '__main__':
    from mmdet.models import build_detector
    from mmcv import ConfigDict

    cfg = ConfigDict(model)
    mdl = build_detector(cfg)
